<!--商品管理 -->
<template>
  <div class="goods">
    <el-container>
      <el-header>
        <!-- <div class="searchBar">
          
        </div> -->
        <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            title="批量删除"
            @click="deleteAll()"
          >批量删除</el-button>
        <el-input
          placeholder="请输入商品编号或者名称"
          v-model="searchGood"
          class="input-with-select"
          style="width:30%;"
        >
          <el-select
            v-model="selectOption"
            slot="prepend"
            placeholder="请选择"
            style="width:130px;"
          >
            <el-option label="商品名称" value="1"></el-option>
            <el-option label="商品编号" value="2"></el-option>
          </el-select>
          <el-button
            slot="append"
            icon="el-icon-search"
            title="点击搜索"
            @click="searchGoods()"
            >搜索商品</el-button
          >
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-plus"
          title="添加商品"
          style="margin-left:14px"
          v-on:click="dialogVisible = true"
          >添加商品</el-button
        >
        <el-dialog title="添加商品" :visible.sync="dialogVisible" width="60%">
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="addForm"
          >
            <el-form-item label="名称">
              <el-row>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.name"
                    placeholder="请输入该商品的名称"
                  ></el-input>
                </el-col>
                <el-col :span="2">价格</el-col>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.price"
                    placeholder="请输入该商品的价格"
                  ></el-input>
                </el-col>
                <el-col :span="2">类型</el-col>
                <el-col :span="6">
                  <el-select v-model="addForm.cid">
                    <el-option
                      v-for="item in categoryOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="库存">
              <el-row>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.stock"
                    placeholder="请输入该商品库存"
                  ></el-input>
                </el-col>
                <el-col :span="2">规格</el-col>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.specification"
                    placeholder="请输入该商品规格"
                  ></el-input>
                </el-col>
                <el-col :span="2">单位</el-col>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.unit"
                    placeholder="请输入该商品单位"
                  ></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="upload-demo"
                action="1"
                :file-list="fileList"
                :http-request="UploadImage"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述">
              <el-row>
                <el-col>
                  <el-input
                    type="textarea"
                    v-model="addForm.description"
                    placeholder="请填写该商品的相关描述"
                  ></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addGoodsList()">确 定</el-button>
          </span>
        </el-dialog>
        <el-button
          type="success"
          icon="el-icon-refresh"
          title="刷新"
          style="margin-left:14px"
          @click="refresh()"
          >刷新</el-button
        >
      </el-header>
      <el-main>
        <div>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <span class="total">共有数据 {{totalSize}} 条</span>
          <template>
            <el-table
              :data="tableData"
              style="width: 100%;margin-top:2%;"
              show-overflow-tooltip
            >
              <el-table-column
              align ="center"
              width = "60">
              <template slot-scope="scope">
                <el-checkbox-group v-model="checkedId" @change="handleCheckedChange">
                  <el-checkbox :key="scope.row.id" :label="scope.row.id">{{""}}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
              <el-table-column
                label="商品名称"
                prop="name"
                width="180"
              ></el-table-column>
              <el-table-column label="缩略图" align="center" height="10px">
                <template slot-scope="scope">
                  <el-popover placement="right" title="" trigger="hover">
                    <img
                      :src="scope.row.imgList[0].url"
                      style="height: 150px;width: 150px"
                    />
                    <img
                      slot="reference"
                      :src="scope.row.imgList[0].url"
                      :alt="scope.row.imgList[0].url"
                      style="max-height: 25px;max-width: 25px"
                    />
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column
                label="类型"
                prop="category"
                width="180"
              ></el-table-column>
              <el-table-column
                label="价格"
                prop="price"
                width="180"
              ></el-table-column>
              <el-table-column label="库存" prop="stock"></el-table-column>
              <el-table-column
                label="描述"
                prop="description"
                width="*"
              ></el-table-column>
              <el-table-column
                label="状态"
                prop="_status"
                width="180"
              ></el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="
                      handleEdit(scope.$index, scope.row),
                        (dialogVisible1 = true)
                    "
                    >修改</el-button
                  >
                  <el-dialog
                    title="修改商品"
                    :visible.sync="dialogVisible1"
                    width="60%"
                  >
                    <el-form
                      :label-position="labelPosition"
                      label-width="80px"
                      :model="fixForm"
                    >
                      <el-form-item label="名称">
                        <el-row>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.name"
                              placeholder="请输入该商品的名称"
                            ></el-input>
                          </el-col>
                          <el-col :span="2">价格</el-col>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.price"
                              placeholder="请输入该商品的价格"
                            ></el-input>
                          </el-col>
                          <el-col :span="2">类型</el-col>
                          <el-col :span="6">
                            <el-select v-model="fixForm.cid">
                              <el-option
                                v-for="item in categoryOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              >
                              </el-option>
                            </el-select>
                          </el-col>
                        </el-row>
                      </el-form-item>
                      <el-form-item label="库存">
                        <el-row>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.stock"
                              placeholder="请输入该商品库存"
                            ></el-input>
                          </el-col>
                          <el-col :span="2">规格</el-col>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.specification"
                              placeholder="请输入该商品规格"
                            ></el-input>
                          </el-col>
                          <el-col :span="2">单位</el-col>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.unit"
                              placeholder="请输入该商品单位"
                            ></el-input>
                          </el-col>
                        </el-row>
                      </el-form-item>
                      <el-form-item label="图片">
                        <el-upload
                          class="upload-demo"
                          action="1"
                          :on-remove="handleRemove"
                          :file-list="fileList"
                          :http-request="UploadImage"
                          list-type="picture"
                        >
                          <el-button size="small" type="primary"
                            >点击上传</el-button
                          >
                          <div slot="tip" class="el-upload__tip">
                            只能上传jpg/png文件，且不超过500kb
                          </div>
                        </el-upload>
                      </el-form-item>
                      <el-form-item label="描述">
                        <el-row>
                          <el-col>
                            <el-input
                              type="textarea"
                              v-model="fixForm.description"
                              placeholder="请填写该商品的相关描述"
                            ></el-input>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible1 = false,fileList = []"
                        >取 消</el-button
                      >
                      <el-button type="primary" @click="fixGoodsList()"
                        >确 定</el-button
                      >
                    </span>
                  </el-dialog>
                  <el-button
                    size="mini"
                    type="danger"
                    @click.native.prevent="
                      handleDelete(scope.$index, scope.row.id)
                    "
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </el-main>
      <el-footer>
        <el-button @click="pre" :disabled="preBool">上一页</el-button>
        <el-input
          v-model="pageNum"
          readonly="readonly"
          style="width:60px;"
        ></el-input>
        <el-button @click="add" :disabled="addBool">下一页</el-button>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "Goods",
  data() {
    return {
      // 搜索栏
      searchGood: "",
      selectOption: "",
      // 弹出框
      dialogVisible: false,
      dialogVisible1: false,
      // form表单对齐方式
      labelPosition: "right",
      // 商品类别
      category: [],
      categoryOption: [],
      tableData: [],
      addForm: {
        name: "",
        price: "",
        specification: "",
        unit: "",
        imageUrl: [],
        description: "",
        stock: "",
        cid: ""
      },
      // 展示用的图片数组
      fileList: [],
      // 提交用的图片数组
      imageList: [],
      // 修改列表
      fixForm: {
        id: "",
        name: "",
        price: "",
        specification: "",
        unit: "",
        imageUrl: [],
        description: "",
        stock: "",
        cid: ""
      },
      // 分页
      pageNum: 1,
      addBool: false,
      preBool: true,
      pageSize: 10,
      totalPages: "",
      totalSize: "",
      pages: "",

      // 全选
      checkAll: false,
      checkedId: [],
      isIndeterminate: true,
    };
  },
  watch: {
    pageNum: function(Val) {
      if (Val === 1) {
        this.preBool = true;
        this.addBool = false;
      } else if (Val === this.totalPages) {
        this.addBool = true;
        this.preBool = false;
      } else {
        this.preBool = false;
        this.addBool = false;
      }
    }
  },
  created() {
    this.getGoodsListPage();
    this.getGoodsCategory();
  },

  components: {},

  filters: {},

  computed: {},

  methods: {
    handleCheckedChange(value = []) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tableData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
      console.log(this.checkedId)
    },
    handleCheckAllChange(val) {
      this.checkedId = []
      this.checkAll = val;
      this.isIndeterminate = !val;
      if(this.checkAll) {
        this.tableData.forEach(data => {
          this.checkedId.push(data.id);
        });
      }
      console.log(this.checkedId)
    },
    handleEdit(index, row) {
      // console.log(index, row);
      this.fixForm = row;
      for (let i in this.categoryOption) {
        if (row.category === this.categoryOption[i].label) {
          this.fixForm.cid = this.categoryOption[i].value;
        }
      }
      if (row.imgList.url == '') {
        this.fileList = [];
      } else {
        
        this.fileList = row.imgList;
      }
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.fileList = fileList;
    },
    handleDelete(index, id) {
      // console.log(index, id);
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteGoodsList(index, id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // handlePreview(file) {
    // console.log(file);
    // },
    add() {
      if (this.pageNum < this.totalPages) {
        this.pageNum++;
        this.getGoodsListPage();
      } else {
        this.addBool = true;
      }
    },
    pre() {
      if (this.pageNum > 1) {
        this.pageNum--;
        this.getGoodsListPage();
      } else {
        this.preBool = true;
      }
    },
    Success(index) {
      this.$message.success(index);
    },
    Fail(index) {
      this.$message.error(index);
    },
    refresh() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.searchGood = "";
      this.getGoodsListPage();
    },
    UploadImage(param) {
      // console.log(param)
      const formData = new FormData();
      formData.append("file", param.file);
      this.axios
        .post("/api/upload", formData)
        .then(res => {
          // console.log(res);
          if (res.data.code === 200) {
            this.imageList.push(res.data.data);
            // console.log(this.imageList);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 获取商品的分类
    getGoodsCategory() {
      this.axios
        .get("/api/goodsCategory")
        .then(res => {
          // console.log(res.data);
          if (res.data.code === 200) {
            let bufferList = [];
            // this.category = res.data.data.list;
            for (let item in res.data.data.list) {
              let i = new Object();
              i.label = res.data.data.list[item].name;
              i.value = res.data.data.list[item].id;
              bufferList.push(i);
            }
            this.categoryOption = bufferList;
          }
          // console.log(this.categoryOption);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 获取所有商品
    getGoodsList() {
      this.axios
        .get("/api/goods")
        .then(res => {
          // console.log(res.data);
          let list = res.data.data.goodsList;
          if (res.data.code === 200) {
            for (let item of list) {
              item._status = item.status ? "启用" : "禁用";
            }
            this.tableData = list;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getGoodsListPage() {
      this.axios
        .put("/api/goods", {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        .then(res => {
          console.log(res.data.data);
          if (res.data.code === 200) {
            // console.log('get');
            this.totalPages = res.data.data.totalPages;
            this.totalSize = res.data.data.totalSize;
            this.pageNum = res.data.data.pageNum;
            this.pageSize = res.data.data.pageSize;
            for (let item of res.data.data.content) {
              item._status = item.status ? "启用" : "禁用";
              item.imgList = item.imgList ? item.imgList : [{}];
            }
            this.tableData = res.data.data.content;
          }else{
            this.totalPages = 0;
            this.totalSize = 0;
            this.tableData = [];
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 添加商品
    addGoodsList() {
      // console.log({
      //       name: this.addForm.name,
      //       price: this.addForm.price,
      //       specification: this.addForm.specification,
      //       unit: this.addForm.unit,
      //       imageUrl: this.addForm.imageUrl,
      //       description: this.addForm.description,
      //       stock: this.addForm.stock,
      //       cid: this.addForm.cid
      //     });
      if (
        this.imageList === "" ||
        this.addForm.name === "" ||
        this.addForm.price === "" ||
        this.addForm.specification === "" ||
        this.addForm.unit === "" ||
        this.addForm.imageUrl === "" ||
        this.addForm.description === "" ||
        this.addForm.stock === "" ||
        this.addForm.cid === ""
      ) {
        this.Fail("信息不足，无法添加");
      } else {
        this.addForm.imageUrl = this.imageList;
        this.axios
          .post("/api/goods", {
            name: this.addForm.name,
            price: this.addForm.price,
            specification: this.addForm.specification,
            unit: this.addForm.unit,
            imageUrl: this.addForm.imageUrl,
            description: this.addForm.description,
            stock: this.addForm.stock,
            cid: this.addForm.cid
          })
          .then(res => {
            console.log(res);
            this.imageList = [];
            if (res.data.code === 200) {
              this.dialogVisible = false;
              this.Success("添加成功");
              this.getGoodsListPage();
              this.addForm = [];
              this.fileList = [];
            } else {
              this.Fail("添加失败");
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    // 修改商品
    fixGoodsList() {
      this.fileList.forEach(item => {
        this.imageList.push(item.url);
      });
      if (
        this.imageList === "" ||
        this.fixForm.id === "" ||
        this.fixForm.name === "" ||
        this.fixForm.price === "" ||
        this.fixForm.specification === "" ||
        this.fixForm.unit === "" ||
        this.fixForm.imageUrl === "" ||
        this.fixForm.description === "" ||
        this.fixForm.stock === "" ||
        this.fixForm.cid === ""
      ) {
        this.Fail("信息不足，无法修改。请填写全部信息");
      } else {
        this.fixForm.imageUrl = this.imageList;
        this.axios
          .post("/api/goods", {
            id: this.fixForm.id,
            name: this.fixForm.name,
            price: this.fixForm.price,
            specification: this.fixForm.specification,
            unit: this.fixForm.unit,
            imageUrl: this.fixForm.imageUrl,
            description: this.fixForm.description,
            stock: this.fixForm.stock,
            cid: this.fixForm.cid
          })
          .then(res => {
            // console.log(res);
            this.imageList = [];
            if (res.data.code === 200) {
              this.dialogVisible1 = false;
              this.Success("修改成功");
              this.getGoodsListPage();
              this.imageList = [];
              this.fileList = [];
            } else {
              this.Fail("修改失败");
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    // 删除商品
    deleteGoodsList(index, id) {
      this.axios
        .delete("/api/goods", {
          params: {
            ids: id
          }
        })
        .then(res => {
          // console.log(res);
          if (res.data.code === 200) {
            this.Success("删除成功");
            this.tableData.splice(index, 1);
            this.getGoodsListPage();
          } else {
            this.Fail("删除失败");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    searchGoods() {
      if (this.selectOption === "1") {
        // console.log(this.selectOption);
        // console.log(this.searchGood);
        this.axios
          .put("/api/goods", {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.searchGood
          })
          .then(res => {
            // console.log(res.data);
            if (res.data.code === 200) {
              this.Success("查询成功");
              this.tableData = [];
              this.totalPages = res.data.data.totalPages;
              this.totalSize = res.data.data.totalSize;
              this.pageNum = res.data.data.pageNum;
              this.pageSize = res.data.data.pageSize;
              for (let item of res.data.data.content) {
                item._status = item.status ? "启用" : "禁用";
              }
              this.tableData = res.data.data.content;
            } else {
              this.Fail("查找失败");
            }
          })
          .catch(error => {
            console.log(error);
          });
      } else if (this.selectOption === "2") {
        this.axios
          .put("/api/goods", {
            pageSize: this.pageSize,
            pageNum: this.pageNum,
            id: this.searchGood
          })
          .then(res => {
            // console.log(res.data);
            if (res.data.code === 200) {
              this.Success("查询成功");
              this.tableData = [];
              this.totalPages = res.data.data.totalPages;
              this.totalSize = res.data.data.totalSize;
              this.pageNum = res.data.data.pageNum;
              this.pageSize = res.data.data.pageSize;
              for (let item of res.data.data.content) {
                item._status = item.status ? "启用" : "禁用";
              }
              this.tableData = res.data.data.content;
            } else {
              this.Fail("查找失败");
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    deleteAll() {
      var data = {
        ids: this.checkedId
      }
      var params = this.qs.stringify(data, { indices: false })
      this.axios.delete('/api/goods?'+params
      ).then(response => {
        console.log(response);
        if(response.data.code == 200) {
          this.getGoodsListPage();
          this.Success("删除成功");
        } else {
          this.Fail("删除失败");
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
};
</script>
<style scoped>
.total {
  font-size: 14px;
  margin-left: 50px;
  color: #606266;
}
.goods {
  width: 100%;
  height: 100%;
}
.el-container {
  width: 100%;
  height: 100%;
}
.el-header {
  line-height: 60px;
  width: 100%;
}
.el-main {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}
.el-main::-webkit-scrollbar {
  display: none;
}
.el-footer {
  line-height: 60px;
  text-align: right;
}
/* .searchBar {
  width: 100%;
  height: 5%;
  margin-top: 15px;
} */
.el-input {
  width: 93%;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>